


"""
数据IO处理工厂
"""

import copy
import json

from testapp.models import Apicat, Apidata, Casedata, Casecat, Prvbefcase, PlanlinkCase, Caseplan, Vendata, Commonmethod, \
    Reportdata, PlanExRecord, Apioldata, SchedulData, ImportRecord, Vendata, Commethoddes, EnvdbConfigdata
from django.db.models import Q
from django.core.paginator import Paginator


class DataIOFactory(object):
    def __init__(self):
        self.list_api = []

    def getEnv(self, data):
        try:
            # 使用ORM获取所有学生的信息
            obj_envs = list(Vendata.objects.filter(Q(isdelete=0) &  (Q(id__icontains=data['inputstr']) |
                                                               Q(name__icontains=data['inputstr']) |
                                                               Q(url__icontains=data['inputstr']) |
                                                               Q(db__icontains=data['inputstr']) |
                                                               Q(dbuser__icontains=data['inputstr'])
                                                               )).values().order_by('-id'))
            res = {}
            res['totalCount'] = len(obj_envs)
            paga_list = Paginator(obj_envs, data['pageSize'])
            res['envs'] = list(paga_list.page(data['currentPage']))
            return True, res
        except Exception as e:
            return False, str(e)

    def add_env(self, envData):
        """#添加环境："""
        try:
            obj_env = Vendata(name=envData['name'], url=envData['url'], db=envData['db'],
                              dbuser=envData['dbuser'], dbpwd=envData['dbpwd'], dbport=envData['dbport'],
                              dbname=envData['dbname'],
                              global_toke=envData['global_toke'], resapi=envData['resapi'])
            obj_env.save()
            for data in envData['dblst']:
                self.add_data_conf(data, obj_env.id)
            return True, "新增环境成功"
        except Exception as e:
            return False, str(e)

    def add_data_conf(self, data, env_id):
        '''
        添加环境的数据库配置
        '''
        try:
            obj_data = EnvdbConfigdata(name=data['name'], parname=data['parname'], db=data['db'],
                                       dbuser=data['dbuser'], dbpwd=data['dbpwd'], dbport=data['dbport'],
                                       dbname=data['dbname'], type=data['type'], envid_id=env_id)
            obj_data.save()
            return True, '数据库配置信息添成功'
        except Exception as e:
            return False, str(e)

    def get_data_conf(self, env_id):
        '''
        通过环境id获取数据库配置
        '''
        try:
            obj_dbs = list(EnvdbConfigdata.objects.filter(Q(envid_id=env_id) & Q(isdelete=0)).values())
            return True, obj_dbs
        except Exception as e:
            return False, str(e)

    def get_data_conf_info(self, env_id, type, name):
        try:
            if name is None or name == '':
                obj_dbs = list(EnvdbConfigdata.objects.filter(
                    Q(envid_id=env_id) & Q(isdelete=0) & Q(type=type)).values())
                if len(obj_dbs) == 0:
                    return False, '数据库配置名称值参有误或环境配置有误'
                else:
                    return True, obj_dbs[0]
            obj_dbs = list(EnvdbConfigdata.objects.filter(Q(envid_id=env_id) & Q(isdelete=0) & Q(type=type) & Q(name=name)).values())
            if len(obj_dbs) == 0 or len(obj_dbs) > 1:
                return False, '数据库配置名称值参有误或环境配置有误'
            else:
                return True, obj_dbs[0]
        except Exception as e:
            return False, str(e)

    def updata_env(self, data):
        """
        更新环境信息
        """
        try:
            self.del_db_cnf(data['dblst'], data['id'])
            for cnf in data['dblst']:
                isOK, result = self.updata_db_cnf(cnf, data['id'])
                if isOK == False:
                    return isOK. result
            obj_env = Vendata.objects.get(id=data['id'])
            obj_env.name = data['name']
            obj_env.url = data['url']
            obj_env.db = data['db']
            obj_env.dbuser = data['dbuser']
            obj_env.dbpwd = data['dbpwd']
            obj_env.dbport = data['dbport']
            obj_env.dbname = data['dbname']
            obj_env.global_toke = data['global_toke']
            obj_env.resapi = data['resapi']
            obj_env.save()
            return True, '插入数据成功'
        except Exception as e:
            return False, str(e)

    def updata_db_cnf(self, cnf, env_id):
        try:
            if cnf.__contains__('id'):
                obj_db = EnvdbConfigdata.objects.get(id=cnf['id'])
                obj_db.name = cnf['name']
                obj_db.parname = cnf['name']
                obj_db.db = cnf['db']
                obj_db.dbuser = cnf['dbuser']
                obj_db.dbpwd = cnf['dbpwd']
                obj_db.dbport = cnf['dbport']
                obj_db.dbname = cnf['dbname']
                obj_db.save()
            else:
                obj_data = EnvdbConfigdata(name=cnf['name'], parname=cnf['parname'], db=cnf['db'],
                                           dbuser=cnf['dbuser'], dbpwd=cnf['dbpwd'], dbport=cnf['dbport'],
                                           dbname=cnf['dbname'], type=cnf['type'], envid_id=env_id)
                obj_data.save()
            return True, '更新数据成功'
        except Exception as e:
            return False, str(e)

    def del_db_cnf(self, cnflst, env_id):
        """
        更新时删除数据库配置
        """
        try:
            obj_dbs = list(EnvdbConfigdata.objects.filter(Q(envid_id=env_id) & Q(isdelete=0)).values())
            for db in obj_dbs:
                for cnf in cnflst:
                    if cnf.__contains__('id') == False:
                        continue
                    if db['id'] == cnf['id']:
                        break
                if len(cnflst) == 0 or cnf.__contains__('id') == False or db['id'] != cnf['id']:
                    obj_db = EnvdbConfigdata.objects.get(id=db['id'])
                    obj_db.isdelete = 1
                    obj_db.save()
        except Exception as e:
            pass



    #更新树节点
    def updateCat(self, data):
        """
        更新树节点
        """
        try:
            if data['type'] == 0:
                cat_obj = Apicat.objects.get(id=data['id'])
                cat_obj.name = data['name']
                cat_obj.save()
            else:
                cat_obj = Casecat.objects.get(id=data['id'])
                cat_obj.name = data['name']
                cat_obj.save()
            return True, '修改成功'
        except Exception as e:
            return False, str(e)


    def Catagery(self, obj):
        """
        实现级联
        """
        i = 3
        while (i > 0):
            for item in obj:
                item['isdel'] = 1 if item['level'] == 1 else 0
                item['isadd'] = 0 if (item['level'] == 1 or item['level'] == 2) else 1
                if item['level'] == i:
                    for item_a in obj:
                        if item_a['level'] == i - 1 and item['parentid'] == item_a['id']:
                            if item_a.__contains__('children') is False:
                                item_a['children'] = []
                            item_a['children'].append(copy.deepcopy(item))
                            item['isdelete'] = 1
            i -= 1
        apicat = []
        for item in obj:
            if item['isdelete'] != 1:
                apicat.append(copy.deepcopy(item))
        return apicat


    def getApi(self, data):
        """
        查出api数据，递归
        """
        list_api = []
        if data['level'] == 3 :
            return list(Apidata.objects.filter(Q(catid=data['nodeid']) & (Q(name__icontains=data['inputstr']) |
                                                                          Q(id__icontains=data['inputstr']) |
                                                                          Q(api__icontains=data['inputstr']) |
                                                                          Q(apimethod__icontains=data['inputstr']))
                                               ).values().order_by('-id'))
        if data['level'] < 3:
            obj_cat = list(Apicat.objects.filter(Q(parentid=data['nodeid'])).values())
            for item in obj_cat:
                list_api += list(self.getApi({'nodeid': item['id'], 'level': item['level'], 'inputstr': data['inputstr']}))
        return list_api


    def queryApi(self, data):
        """
        查询用例，实现分页操作
        """
        res = {}
        list_case = self.getApi(data)
        res['totalCount'] = len(list_case)
        paga_list = Paginator(list_case, data['pageSize'])
        res['apis'] = list(paga_list.page(data['currentPage']))
        return res



    def getCase(self, data):
        """
        查询case数据，递归
        支持字段模糊搜索
        """
        list_case = []
        if data['level'] == 3:
            return list(Casedata.objects.filter(Q(catid=data['nodeid']) & Q(isdelete=0) & (Q(name__icontains=data['inputstr']) |
                                                                          Q(id__icontains=data['inputstr']) |
                                                                          Q(api__icontains=data['inputstr']) |
                                                                          Q(apimethod__icontains=data['inputstr']) |
                                                                          Q(headers__icontains=data['inputstr']) |
                                                                          Q(body__icontains=data['inputstr']))
                                                                           ).values().order_by('-id'))
        if data['level'] < 3:
            obj_cat = list(Casecat.objects.filter(Q(parentid=data['nodeid'])).values())
            for item in obj_cat:
                list_case += list(self.getCase({'nodeid': item['id'], 'level': item['level'], 'inputstr': data['inputstr']}))
        return list_case

    def queryCase(self, data):
        """
        查询用例，实现分页操作
        """
        res = {}
        list_case = self.getCase(data)
        res['totalCount'] = len(list_case)
        paga_list = Paginator(list_case, data['pageSize'])
        res['cases'] = list(paga_list.page(data['currentPage']))
        return res


    def format_headers(self, param):
        """
        格式化请求头
        :param param:excel里读出出来的header，是从浏览器f12里直接copy的
        :return:
        """
        if param is None:
            return 'Headers为空'
        list_header = param.split('\n')
        headers = {}

        for li in list_header:
            buff = li.split(':')
            try:
                headers[buff[0]] = buff[1].strip()
            except IndexError:
                return 'Headers格式不对'
        return headers

    #添加用例
    def addCase(self, caseData):
        #判断公共方法数据是否OK
        isOK, result = self.judgeCom(caseData['commoFrom'], 0)
        if isOK == False:
            return isOK, result
        elif isOK == 3:
            precommon = []
        else:
            precommon = result

        isOK, result = self.judgeCom(caseData['sqlFrom'], 3)
        if isOK == False:
            return isOK, result
        elif isOK == 3:
            sql = []
        else:
            sql = result

        isOK, result = self.judgeCom(caseData['parcommonFrom'], 4)
        if isOK == False:
            return isOK, result
        elif isOK == 3:
            parcommon = []
        else:
            parcommon = result

        isOK, result = self.judgeCom(caseData['rescommonFrom'], 1)
        if isOK == False:
            return isOK, result
        elif isOK == 3:
            rescommon = []
        else:
            rescommon = result

        isOK, result = self.insertCase(caseData['apiFrom'])

        if isOK:
            case_id = result

            isOK, result = self.addCommonmehtod(precommon, 0, case_id)
            if isOK == False:
                return isOK, '前置' + str(result)
            isOK, result = self.addCommonmehtod(sql, 3, case_id)
            if isOK == False:
                return isOK, 'SQL' + str(result)
            isOK, result = self.addCommonmehtod(parcommon, 4, case_id)
            if isOK == False:
                return isOK, '参数化' + str(result)
            isOK, result = self.addCommonmehtod(rescommon, 1, case_id)
            if isOK == False:
                return isOK, '后置' + str(result)
        else:
            return isOK, result
        return True, '添加用例成功'

    #插入用例数据，返回用例id
    def insertCase(self, caseData):
        try:
            obj_case = Casedata(name=caseData['name'], catid_id=caseData['catid'], api=caseData['api'], apimethod=caseData['apimethod'],
                                headers=caseData['headers'], body=caseData['body'], checkrestype=int(caseData['checkrestype']),
                                checkmethod=caseData['checkmethod'], checkdata=caseData['checkdata'], comments=caseData['comments'])
            obj_case.save()
            return True, obj_case.id
        except Exception as e:
            return False, e

    #'前置或后置，0：前置自动定义，1是后置自定义，3、是操作数据库，4是参数化'
    def addCommonmehtod(self, common, comType, case_id):
        if len(common) > 0:
            for data in common:
                if self.judgeJson(data):
                    try:
                        obj_com = Prvbefcase(caseid_id=case_id, method=data['method'], f_params=data['f_params'],
                                             s_params=data['s_params'], t_params=data['t_params'], result=data['result'], preorbef=comType)
                        obj_com.save()
                    except Exception as e:
                        return False, e
        return True, '新增成功'



    #判断用例里的公共方法是否有传入，是否有末写好的用例
    def judgeCom(self, common, index):
        judge = False
        result = []
        firstd = {}
        for key in common:
            if key == 'dynamicItem':
                if len(common[key]) > 0 and judge == False and index == 0:
                    return False, '请优化一下前置自定义方法'
                elif len(common[key]) > 0 and judge == False and index == 1:
                    return False, '请优化一下后置自定义方法'
                elif len(common[key]) > 0 and judge == False and index == 3:
                    return False, '请优化一下数据库操作'
                elif len(common[key]) > 0 and judge == False and index == 4:
                    return False, '请优化一下参数化'
            else:
                if common[key] != '':
                    judge = True
                firstd[key] = common[key]

        if judge:
            result.append(firstd)
            if len(common['dynamicItem']) > 0:
                result.extend(common['dynamicItem'])
            return judge, result
        else:
            return 3, '没传参，不用保存'

    #判断json串是否有数据
    def judgeJson(self, data):
        judge = False
        for key in data:
            if data[key] != '' and key != 'id':
                judge = True
        return judge



    #获取用例
    def getCaseDetail(self, caseid):
        isOK, result = self.getCasedata(caseid)
        if isOK:
            caseData = result
            if len(caseData) == 0:
                return False, '未找到用例信息'
        else:
            return isOK, result

        isOK, result = self.getCaseCommon(caseid)
        if isOK:
            commonData = result
        else:
            return isOK, result

        detailData = {}
        detailData['apiFrom'] = caseData[0]
        if len(commonData) == 0:
            detailData['commoFrom'] = {}
            detailData['sqlFrom'] = {}
            detailData['parcommonFrom'] = {}
            detailData['rescommonFrom'] = {}
            return True, detailData
        else:
            commo = []
            sql = []
            par = []
            res = []
            for data in commonData:
                data.pop('caseid_id')
                if data['preorbef'] == 0:
                    data.pop('preorbef')
                    commo.append(data)
                elif data['preorbef'] == 3:
                    data.pop('preorbef')
                    sql.append(data)
                elif data['preorbef'] == 4:
                    data.pop('preorbef')
                    par.append(data)
                elif data['preorbef'] == 1:
                    data.pop('preorbef')
                    res.append(data)
            if len(commo) == 0:
                detailData['commoFrom'] = {}
            else:
                detailData['commoFrom'] = self.assCommon(commo)

            if len(sql) == 0:
                detailData['sqlFrom'] = {}
            else:
                detailData['sqlFrom'] = self.assCommon(sql)

            if len(par) == 0:
                detailData['parcommonFrom'] = {}
            else:
                detailData['parcommonFrom'] = self.assCommon(par)

            if len(res) == 0:
                detailData['rescommonFrom'] = {}
            else:
                detailData['rescommonFrom'] = self.assCommon(res)

        return True, detailData


    #拼装公共方法
    def assCommon(self, common):
        From = {}
        dynamicItem = []
        i = 1
        for item in common:
            if i == 1:
                From = item
                i += 1
            else:
                dynamicItem.append(item)
        From['dynamicItem'] = dynamicItem
        return From


    #获取用例信息
    def getCasedata(self, caseid):
        try:
            obj_case = list(Casedata.objects.filter(Q(id=caseid)).values())
            obj_case = self.popdata((obj_case))
            return True, obj_case
        except Exception as e:
            return False, e

    #获取用例的公共方法
    def getCaseCommon(self, caseid):
        try:
            obj_common = list(Prvbefcase.objects.filter(Q(caseid_id=caseid)).values())
            obj_common = self.popdata(obj_common)
            return True, obj_common
        except Exception as e:
            return False, e

    def popdata(self, datalist):
        if len(datalist) == 0:
            return []
        D_list = []
        for data in datalist:
            data.pop('isdelete')
            data.pop('create_time')
            data.pop('create_user')
            data.pop('updata_time')
            data.pop('updata_user')
            D_list.append(data)
        return D_list



    def updataCaseData(self, caseData):
        # 判断公共方法数据是否OK
        isOK, result = self.judgeUpCom(caseData['commoFrom'], 0)
        if isOK == False:
            return isOK, result
        elif isOK == 3:
            precommon = []
        else:
            precommon = result

        isOK, result = self.judgeUpCom(caseData['sqlFrom'], 3)
        if isOK == False:
            return isOK, result
        elif isOK == 3:
            sql = []
        else:
            sql = result

        isOK, result = self.judgeUpCom(caseData['parcommonFrom'], 4)
        if isOK == False:
            return isOK, result
        elif isOK == 3:
            parcommon = []
        else:
            parcommon = result

        isOK, result = self.judgeUpCom(caseData['rescommonFrom'], 1)
        if isOK == False:
            return isOK, result
        elif isOK == 3:
            rescommon = []
        else:
            rescommon = result
        #更新用例
        isOK, result = self.updataCase(caseData['apiFrom'])

        if isOK:
            case_id = result
            isOK, result = self.updataCommonmehtod(precommon, 0, case_id)
            if isOK == False:
                return isOK, '前置' + str(result)
            isOK, result = self.updataCommonmehtod(sql, 3, case_id)
            if isOK == False:
                return isOK, 'SQL' + str(result)
            isOK, result = self.updataCommonmehtod(parcommon, 4, case_id)
            if isOK == False:
                return isOK, '参数化' + str(result)
            isOK, result = self.updataCommonmehtod(rescommon, 1, case_id)
            if isOK == False:
                return isOK, '后置' + str(result)
        else:
            return isOK, result
        return True, '更新用例成功'

    # 判断用例里的公共方法是否有传入，是否有末写好的用例
    def judgeUpCom(self, common, index):
        judge = False
        result = []
        firstd = {}
        for key in common:
            if key == 'dynamicItem':
                if len(common[key]) > 0 and judge == False and index == 0:
                    return False, '请优化一下前置自定义方法'
                elif len(common[key]) > 0 and judge == False and index == 1:
                    return False, '请优化一下后置自定义方法'
                elif len(common[key]) > 0 and judge == False and index == 3:
                    return False, '请优化一下数据库操作'
                elif len(common[key]) > 0 and judge == False and index == 4:
                    return False, '请优化一下参数化'
            else:
                if common[key] != '' and key != 'id':
                    judge = True
                firstd[key] = common[key]

        if judge:
            result.append(firstd)
            if len(common['dynamicItem']) > 0:
                result.extend(common['dynamicItem'])
            return judge, result
        else:
            return 3, '没传参，不用保存'


    def updataCase(self, caseData):
        try:
            obj_case = Casedata.objects.get(id=caseData['id'])
            obj_case.name = caseData['name']
            obj_case.catid_id = caseData['catid_id']
            obj_case.api = caseData['api']
            obj_case.apimethod = caseData['apimethod']
            obj_case.headers = caseData['headers']
            obj_case.body = caseData['body']
            obj_case.checkrestype = caseData['checkrestype']
            obj_case.checkmethod = caseData['checkmethod']
            obj_case.checkdata = caseData['checkdata']
            obj_case.comments = caseData['comments']
            obj_case.save()
            return True, caseData['id']
        except Exception as e:
            return False, e



    def updataCommonmehtod(self, common, comType, case_id):
        self.delCommonmethod(common, case_id, comType)
        if len(common) > 0:
            for data in common:
                if self.judgeJson(data):
                    if data['id'] == -1:
                        try:
                            obj_com = Prvbefcase(caseid_id=case_id, method=data['method'], f_params=data['f_params'],
                                                 s_params=data['s_params'], t_params=data['t_params'], result=data['result'], preorbef=comType)
                            obj_com.save()
                        except Exception as e:
                            return False, e
                    else:
                        try:
                            obj_com = Prvbefcase.objects.get(id=data['id'])
                            obj_com.method = data['method']
                            obj_com.f_params = data['f_params']
                            obj_com.s_params = data['s_params']
                            obj_com.t_params = data['t_params']
                            obj_com.result = data['result']
                            obj_com.save()
                        except Exception as e:
                            return False, e
        return True, '更新成功'


    def delCommonmethod(self, common, case_id, comType):
        try:
            obj_coms = list(Prvbefcase.objects.filter(Q(caseid_id=case_id) & Q(preorbef=comType)).values())
            if len(obj_coms) > 0:
                for com in obj_coms:
                    if self.judgecomisEmpty(com['id'], common) == False:
                        obj_com = Prvbefcase.objects.get(id=com['id'])
                        obj_com.delete()
                return True, "删除公共方法成功"
        except Exception as e:
            return False, e


    def judgecomisEmpty(self, id, common):
        for data in common:
            if data['id'] == id:
                return True
        return False


    def addPlan(self, plan):
        try:
            # print(type(plan['venid']))
            obj_plan = Caseplan(name=plan['name'], venid_id=plan['venid'], exctime=plan['exctime'], qymsg=plan['qymsg'], webhook=plan['webhook'])
            obj_plan.save()
        except Exception as e:
            return False, str(e)

        #添加定时任务
        if plan['exctime'] is not None or plan['exctime'] != '':
            self.addschedule(plan['exctime'], obj_plan.id, plan['name'], obj_plan.id, jobtype=2)



        isOK, result = self.addPlanCaselink(plan['caselist'], obj_plan.id)
        if isOK:
            return True, '添加计划成功'
        else:
            obj_plan.delete()
            return False, result

    def addschedule(self, schtime, par, name, id, jobtype):
        """
        添加定时数据
        """
        try:
            params = []
            params.append(par)
            params.append(name)
            obj_sch = SchedulData(name=name, schtime=schtime, params=params, jobtype=jobtype, job_id=id)
            obj_sch.save()
        except Exception as e:
            pass

    def updataPlanScheStatus(self, data):
        """
        更新测试计划定时任务状态
        """
        try:
            obj_pan = Caseplan.objects.get(id=data['id'])
            obj_pan.sched = data['scheStatus']
            obj_pan.save()
            return True, '成功'
        except Exception as e:
            return False, str(e)

    def addPlanCaselink(self, arr, plan_id):
        try:
            if len(arr) == 0:
               return True, '没有用例关联'
            obj_links = []  #保存用例link，方便出错后删除
            index = 0
            for case in arr:
                obj_link = PlanlinkCase(planid_id=plan_id, caseid_id=case['id'], index=index)
                obj_link.save()
                obj_links.append(obj_link)
                index += 1
            return True, '添加用例关联成功'
        except Exception as e:
            for obj_link in obj_links:    #出错了，删除相关用例link
                obj_link.delete()
            return False, str(e)

    def getPlanlist(self, data):
        """
        获取测试计划
        """
        try:
            obj_plans = list(Caseplan.objects.filter(Q(isdelete=0) & (Q(id__icontains=data['inputstr']) |
                                                                      Q(name__icontains=data['inputstr'])
                                                                     )).values().order_by('-id'))
            #分页操作
            res={}
            res['totalCount'] = len(obj_plans)
            paga_list = Paginator(obj_plans, data['pageSize'])
            plans = list(paga_list.page(data['currentPage']))
            for obj_plan in plans:
                isOK, result = self.getlinkCount(obj_plan['id'])
                if isOK:
                    obj_plan['caseCount'] = result
                else:
                    return isOK, result
                isOK, result = self.getexcuteCount(obj_plan['id'])
                if isOK:
                    obj_plan['excuteCount'] = result
                else:
                    return isOK, result
                isOK, result = self.getEnvName(obj_plan['venid_id'])
                if isOK:
                    obj_plan['envName'] = result
                else:
                    return isOK, result
            res['plans'] = plans
        except Exception as e:
            return False, str(e)
        return True, res

    def getlinkCount(self, planid):
        try:
            obj_links = list(PlanlinkCase.objects.filter(Q(planid_id=planid)).values())
            return True, len(obj_links)
        except Exception as e:
            return False, str(e)

    def getLinks(self, planid):
        """
        获取计划里关联用例集
        """
        try:
            obj_links = list(PlanlinkCase.objects.filter(Q(planid_id=planid)).values())
            return True, obj_links
        except Exception as e:
            return False, str(e)

    def getexcuteCount(self, planid):
        try:
            link_rec = list(PlanExRecord.objects.filter(Q(planid_id=planid)).values())
            excCount = len(link_rec)
            return True, excCount
        except Exception as e:
            return False, str(e)

    def getEnvName(self, envid):
        if envid is None:
            return True, ''
        try:
            obj_Env = (list(Vendata.objects.filter(Q(id=envid)).values()))[0]
            return True, obj_Env['name']
        except Exception as e:
            return False, str(e)


    def getPlanDetail(self, planid):
        try:
            obj_plans = list(Caseplan.objects.filter(Q(id=planid)).values())
            obj_plan = self.popdata(obj_plans)[0]
            isOK, result = self.getLinkcase(planid)
            if isOK:
                obj_plan['caselist'] = result
                return True, obj_plan
            else:
                return isOK, result
        except Exception as e:
            return False, str(e)


    def getLinkcase(self, planid):
        try:
            cases = []
            obj_links = list(PlanlinkCase.objects.filter(Q(planid_id=planid)).values())
            for link in obj_links:
                cases.append((list(Casedata.objects.filter(Q(id=link['caseid_id'])).values()))[0])
            return True, self.popdata(cases)
        except Exception as e:
            return False, str(e)


    def updataPlan(self, planData):
        try:
            obj_Plan = Caseplan.objects.get(id=planData['id'])
            obj_Plan.name = planData['name']
            obj_Plan.venid_id = planData['venid_id']
            obj_Plan.exctime = planData['exctime']
            obj_Plan.qymsg = planData['qymsg']
            obj_Plan.webhook = planData['webhook']
            self.updateschedule(planData['exctime'], planData['id'], planData['name'], planData['id'], jobtype=2)
            isOK, result = self.updataPlanlinkCase(planData['id'], planData['caselist'])
            if isOK:
                obj_Plan.save()
                return True, '更新数据成功'
            else:
                return isOK, result
        except Exception as e:
            return False, str(e)


    def updateschedule(self, schtime, par, name, id, jobtype):
        """
        添加定时数据
        """
        try:
            obj_sch = SchedulData.objects.filter(Q(jobtype=jobtype) & Q(job_id=id)).values()
            if schtime is None or schtime == '':
                if obj_sch:
                    obj = SchedulData.objects.get(obj_sch[0]['id'])
                    obj.delete()
            else:
                if obj_sch:
                    obj = SchedulData.objects.get(id=obj_sch[0]['id'])
                    params = []
                    params.append(par)
                    params.append(name)
                    obj.name = name
                    obj.schtime = schtime
                    obj.params = params
                    obj.save()
                else:
                    self.addschedule(schtime, par, name, id, jobtype=jobtype)
        except Exception as e:
            pass



    def updataPlanlinkCase(self, planid, caselist):
        try:
            obj_links = PlanlinkCase.objects.filter(Q(planid_id=planid)).values()
            for obj_link in obj_links:
                PlanlinkCase.objects.get(id=obj_link['id']).delete()
            return self.addPlanCaselink(caselist, planid)
        except Exception as e:
            return False, str(e)


    def getCommonMethod(self):
        """
        获取公共方法key
        """
        try:
            coms = {}
            obj_mes = list(Commonmethod.objects.filter(Q(isdelete=0)).values())
            for obj in obj_mes:
                coms[obj['method_name']] = obj['function']
            return True, coms
        except Exception as e:
            return False, str(e)

    def getExcCase(self, caseid):
        """
        获取测试用例详情，
        执行格式
        """
        isOK, result = self.getCasedata(caseid)
        if isOK:
            caseData = result
            if len(caseData) == 0:
                return False, '未找到用例信息'
        else:
            return isOK, result

        isOK, result = self.getCaseCommon(caseid)
        if isOK:
            commonData = result
        else:
            return isOK, result

        detailData = {}
        detailData['apiFrom'] = caseData[0]
        if len(commonData) == 0:
            detailData['commoFrom'] = []
            detailData['sqlFrom'] = []
            detailData['parcommonFrom'] = []
            detailData['rescommonFrom'] = []
            return True, detailData
        else:
            commo = []
            sql = []
            par = []
            res = []
            for data in commonData:
                data.pop('caseid_id')
                if data['preorbef'] == 0:
                    data.pop('preorbef')
                    commo.append(data)
                elif data['preorbef'] == 3:
                    data.pop('preorbef')
                    sql.append(data)
                elif data['preorbef'] == 4:
                    data.pop('preorbef')
                    par.append(data)
                elif data['preorbef'] == 1:
                    data.pop('preorbef')
                    res.append(data)

            detailData['commoFrom'] = commo
            detailData['sqlFrom'] = sql
            detailData['parcommonFrom'] = par
            detailData['rescommonFrom'] = res

        return True, detailData


    def getEnvbyID(self, envid):
        try:
            obj_envs = list(Vendata.objects.filter(Q(id=envid)).values())
            return True, obj_envs[0]
        except Exception as e:
            return False, str(e)

    def addPlanRecord(self, report):
        """
        新增计划执行记录
        """
        try:
            obj_rep = PlanExRecord(excutnum=report['excutnum'], caseCount=report['caseCount'], passCount=report['passCount'],
                                   failCount=report['failCount'], planid_id=report['planid'], thrCount=report['thrCount'],
                                   sevCount=report['sevCount'], secCount=report['secCount'], totalTime=report['totalTime'],
                                   planName=report['planName'])
            obj_rep.save()
            return True, obj_rep.id
        except Exception as e:
            return False, str(e)

    def getExeRecord(self, data):
        """
        获取/查询执行记录
        """
        try:
            # 使用ORM获取所有学生的信息
            obj_records = list(PlanExRecord.objects.filter(Q(isdelete=0) &  (Q(id__icontains=data['inputstr']) |
                                                               Q(planName__icontains=data['inputstr']) |
                                                               Q(excutnum__icontains=data['inputstr'])
                                                               )).values().order_by('-id'))
            res = {}
            res['totalCount'] = len(obj_records)
            paga_list = Paginator(obj_records, data['pageSize'])
            res['exeRecord'] = list(paga_list.page(data['currentPage']))
            return True, res
        except Exception as e:
            return False, str(e)


    def addTestReport(self, report):
        try:
            obj_rep = Reportdata(excutnum=report['excutnum'], planid_id=report['planid'],
                               caseid_id=report['caseid'], testresult=report['testresult'],
                               status=report['status'], casename=report['casename'], elapsedt=report['elapsedt'])
            obj_rep.save()
            return True, obj_rep.id
        except Exception as e:
            return False, str(e)


    def getCaseRoprts(self, caseid):
        """
        获取某个用例所有的非计划的执行记录
        """
        try:
            obj_reps = list(Reportdata.objects.filter(Q(caseid_id=caseid) & Q(planid_id=None)).values().order_by('-id'))
            return True, obj_reps
        except Exception as e:
            return False, str(e)

    def getReportDatail(self, repid):
        """
        获取报告细节字段testresult
        """
        try:
            obj_rep = (list(Reportdata.objects.filter(Q(id=repid)).values()))[0]
            result = json.loads(obj_rep['testresult'])
            return True, result
        except Exception as e:
            return False, str(e)

    def getPlanExRecord(self, planid):
        """
        获取计划执行记录
        """
        try:
            obj_exRec = list(PlanExRecord.objects.filter(Q(planid_id=planid)).values().order_by('-id'))
            return True, obj_exRec
        except Exception as e:
            return False, str(e)

    def getPlanExRecbyNum(self, excutnum):
        """
        通过执行批次编号获取执行记录
        """
        try:
            obj_exRec = list(PlanExRecord.objects.filter(Q(excutnum=excutnum)).values())[0]
            return True, obj_exRec
        except Exception as e:
            return False, str(e)

    def getRecortCaseRepByNum(self, data):
        """
        获取用例报告列表
        """
        try:
            # 使用ORM获取所有学生的信息
            if data['status'] == -1:
                obj_reps = list(Reportdata.objects.filter(Q(isdelete=0) & Q(excutnum=data['excutnum'])).values().order_by('id'))
                res = {}
                res['totalCount'] = len(obj_reps)
                paga_list = Paginator(obj_reps, data['pageSize'])
                res['reports'] = list(paga_list.page(data['currentPage']))
            else:
                obj_reps = list(
                    Reportdata.objects.filter(Q(isdelete=0) & Q(excutnum=data['excutnum']) & Q(status=data['status'])).values().order_by('id'))
                res = {}
                res['totalCount'] = len(obj_reps)
                paga_list = Paginator(obj_reps, data['pageSize'])
                res['reports'] = list(paga_list.page(data['currentPage']))
            return True, res
        except Exception as e:
            return False, str(e)

    def getRecortCaseRep(self, planid, excutnum):
        try:
            obj_reps = list(Reportdata.objects.filter(Q(planid_id=planid) & Q(excutnum=excutnum)).values())
            return True, obj_reps
        except Exception as e:
            return False, str(e)


    def getCatebyName(self, catName):
        try:
            obj_cats = list(Apicat.objects.filter(Q(name=catName)).values())
            return True, obj_cats[0]
        except Exception as e:
            return False, str(e)

    def getCateByparentId(self, catId):
        try:
            obj_cats = list(Apicat.objects.filter(Q(parentid=catId)).values())
            return True, obj_cats
        except Exception as e:
            return False, str(e)


    def getcaseCatebyName(self, catName):
        try:
            obj_cats = list(Casecat.objects.filter(Q(name=catName)).values())
            return True, obj_cats[0]
        except Exception as e:
            return False, str(e)

    def getcaseCateByparentId(self, catId):
        try:
            obj_cats = list(Casecat.objects.filter(Q(parentid=catId)).values())
            return True, obj_cats
        except Exception as e:
            return False, str(e)


    def insertApiCat(self, data):
        try:
            obj_cat = Apicat(name=data['name'], parentid=data['parentid'], level=data['level'])
            obj_cat.save()
            return True, obj_cat
        except Exception as e:
            return False, str(e)

    def insertApi(self, data):
        try:
            obj_api = Apidata(name=data['name'], catid_id=data['catid_id'], api=data['api'],
                              apimethod=data['apimethod'], headers=data['headers'], body=data['body'],
                              response=data['response'])
            obj_api.save()
            return True, "插入数据成功"
        except Exception as e:
            return False, str(e)

    def getApidatabySomepar(self, data):
        try:
            obj_reps = list(Apidata.objects.filter((Q(name=data['name']) & Q(apimethod=['apimethod'])) | ((Q(api=data['api']) & Q(apimethod=data['apimethod'])))).values())
            return True, obj_reps
        except Exception as e:
            return False, str(e)


    def upApidataSaveold(self, newData, oldData):
        try:
            obj_api = Apidata.objects.get(id=oldData['id'])
            obj_opi = Apioldata(oldid=obj_api.id, name=obj_api.name, catid=obj_api.catid_id, api=obj_api.api,
                              apimethod=obj_api.apimethod, headers=obj_api.headers, body=obj_api.body,
                              response=obj_api.response)
            obj_opi.save()
            obj_api.name = newData['name']
            obj_api.api = newData['api']
            obj_api.apimethod = newData['apimethod']
            obj_api.body = newData['body']
            obj_api.response = newData['response']
            obj_api.save()
            return True, "更新成功"
        except Exception as e:
            return False, str(e)

    def getSchedulerData(self, id):
        """
        获取指定的定时任务
        """
        try:
            obj_job = SchedulData.objects.get(id=id)
            return True, obj_job
        except Exception as e:
            return False, str(e)

    def getSchedulerByjobid(self, job_id, jobtype):
        """
        获取指定源数据的定时任务
        """
        try:
            obj_jobs= SchedulData.objects.filter(Q(jobtype=jobtype) & Q(job_id=job_id)).values()
            return True, obj_jobs
        except Exception as e:
            return False, str(e)

    def saveImportRecord(self, record):
        try:
            obj_rec = ImportRecord(viewname=record['viewname'], savename=record['savename'], casecount=record['casecount'],
                                   succount=record['succount'], filcount=record['filcount'])
            obj_rec.save()
            return True, "记录插入成功"
        except Exception as e:
            return False, str(e)

    def getImportRecord(self):
        try:
            obj_recs = list(ImportRecord.objects.filter(Q(isdelete=0)).values().order_by('-id'))
            return True, obj_recs
        except Exception as e:
            return False, str(e)


    def addcommethodes(self, desc):
        #添加描述
        pass


    def getcommethodes(self):
        """
        获取自定义方法描述
        """
        try:
            obj_des = list(Commethoddes.objects.filter(Q(isdelete=0)).values())
            return True, obj_des
        except Exception as e:
            return False, str(e)
